package com.example.service.impl;

import com.example.mapper.TeacherLastPageMapper;
import com.example.pojo.ManagedClass;
import com.example.pojo.Result;
import com.example.pojo.Score;
import com.example.service.TeacherLastPageService;
import com.example.utils.ThreadLocalA;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.List;

@Slf4j
@Service
public class TeacherLastPageImpl implements TeacherLastPageService {

    @Autowired
    private TeacherLastPageMapper teacherLastPageMapper;

    @Override
    public List<ManagedClass> loadAllClasses(Integer teacherId) {
        List<ManagedClass> classList = teacherLastPageMapper.loadAllClasses(teacherId);
        return classList;
    }

    @Override
    public List<String> searchAllSubjectName() {
        return teacherLastPageMapper.searchAllSubjectName();
    }

    @Override
    public Result insertManageClass(ManagedClass managedClass) {

        try {
           /* String classIdStr=managedClass.getClassName().replaceAll("\\D","");
            Integer classId=Integer.parseInt(classIdStr);
            managedClass.setClassId(classId);*/
            if ("".equals(managedClass.getClassName()) || "".equals(managedClass.getSubjectName())||"".equals(managedClass.getPercentageUsualScore())||"".equals(managedClass.getPercentageMidtermScore())||"".equals(managedClass.getPercentageFinalScore())) {
                return Result.fail("请输入完整信息");
            } else if (!teacherLastPageMapper.isExitsManagedClass(managedClass)) {
                //提取百分比转换为数字
                String percentageUsualScore = managedClass.getPercentageUsualScore().replaceAll("%", "");
                BigDecimal percentageUsualScoreNum = new BigDecimal(percentageUsualScore);
                //System.out.println(percentageUsualScoreNum);
                String percentageMidtermScore = managedClass.getPercentageMidtermScore().replaceAll("%", "");
                BigDecimal percentageMidtermScoreNum = new BigDecimal(percentageMidtermScore);
                //System.out.println(percentageMidtermScoreNum);
                String percentageFinalScore = managedClass.getPercentageFinalScore().replaceAll("%", "");
                BigDecimal percentageFinalScoreNum = new BigDecimal(percentageFinalScore);
                //System.out.println(percentageFinalScoreNum);
                //检验相加是否为100
                if (percentageUsualScoreNum.add(percentageMidtermScoreNum).add(percentageFinalScoreNum).compareTo(new BigDecimal(100)) != 0) {
                    return Result.fail("输入百分比有误");
                }
                if(teacherLastPageMapper.classsHasBeenManaged(managedClass.getClassName(),managedClass.getSubjectName())){
                    return Result.fail("该班级该学科已被管理!");
                }
                teacherLastPageMapper.insertManageClass(managedClass);
                return Result.success("添加成功");
            } else {
                return Result.fail("该班级已添加!");
            }
        } catch (Exception e) {
            log.error("添加班级失败" + e.getMessage());
            if(e.getMessage().contains("For input string: \"\"")) {
                return Result.fail("请输入信息");
            }else if(e.getMessage().contains("'class_id' cannot be null")){
                return Result.fail("不存在该班级");
            }
            return Result.fail("添加失败"+e.getMessage());
        }
    }

    @Transactional(rollbackFor = {Exception.class})//添加事务管理
    @Override
    public Result updateManageClass(ManagedClass managedClass) {

        try {
      /*      String classIdStr=managedClass.getClassName().replaceAll("\\D","");
            String newClassIdStr=managedClass.getNewClassName().replaceAll("\\D","");
            Integer classId=Integer.parseInt(classIdStr);
            Integer newClassId=Integer.parseInt(newClassIdStr);
            managedClass.setClassId(classId);
            managedClass.setNewClassId(newClassId);*/
            if ("".equals(managedClass.getClassName()) || "".equals(managedClass.getNewSubjectName())|| "".equals(managedClass.getPercentageUsualScore())||  "".equals(managedClass.getPercentageMidtermScore())|| "".equals(managedClass.getPercentageFinalScore())) {
                return Result.fail("请输入完整信息");
            } else if (teacherLastPageMapper.isManagedClass(managedClass)||!teacherLastPageMapper.isExitsNewManagedClass(managedClass)) {
                //提取百分比转换为数字
                String percentageUsualScore = managedClass.getPercentageUsualScore().replaceAll("%", "");
                BigDecimal percentageUsualScoreNum = new BigDecimal(percentageUsualScore);

                String percentageMidtermScore = managedClass.getPercentageMidtermScore().replaceAll("%", "");
                BigDecimal percentageMidtermScoreNum = new BigDecimal(percentageMidtermScore);

                String percentageFinalScore = managedClass.getPercentageFinalScore().replaceAll("%", "");
                BigDecimal percentageFinalScoreNum = new BigDecimal(percentageFinalScore);

                //检验相加是否为100
                if (percentageUsualScoreNum.add(percentageMidtermScoreNum).add(percentageFinalScoreNum).compareTo(new BigDecimal(100)) != 0) {
                    return Result.fail("输入百分比有误");
                }
                Integer earnCredit=teacherLastPageMapper.inqueryEarnCredit(managedClass); //查询新课程的学分

                List<Score> scores = teacherLastPageMapper.selectManageClassStudentScore(managedClass);//查询需要修改的课程的该班级学生成绩

                teacherLastPageMapper.updateManageClass(managedClass);//修改课程信息
                if(scores.size()!=0) {
                    scores.forEach(score -> {
                        BigDecimal scoreNum=(score.getUsualScore().multiply(percentageUsualScoreNum).divide(new BigDecimal(100)).add(score.getMidtermScore().multiply(percentageMidtermScoreNum).divide(new BigDecimal(100))).add(score.getFinalScore().multiply(percentageFinalScoreNum).divide(new BigDecimal(100))));
                        score.setNewSubjectName(managedClass.getNewSubjectName());
                        score.setNewSemester(managedClass.getNewSemester());
                        score.setScore(scoreNum);
                        if(scoreNum.compareTo(new BigDecimal(60))>=0){
                            score.setEarnCredit(earnCredit);
                        }else {
                            score.setEarnCredit(0);
                        }
                    });
                    teacherLastPageMapper.updateManageClassStudentScore(scores);//将所修改的课程的学生成绩做对应修改
                }
                return Result.success("修改成功");
            } else {
                return Result.fail("该班级该学科已被管理!");
            }
        }catch (Exception e){
            log.error("修改班级失败" + e.getMessage());

            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚事务

            if(e.getMessage().contains("For input string: \"\"")) {
                return Result.fail("请输入信息");
            }
            return Result.fail("修改失败"+e.getMessage());
        }
    }

    @Transactional(rollbackFor = {Exception.class})//添加事务管理
    @Override
    public Result deleteManageClass(ManagedClass managedClass) {

        try {
            /*String classIdStr=managedClass.getClassName().replaceAll("\\D","");
            Integer classId=Integer.parseInt(classIdStr);
            managedClass.setClassId(classId);*/
            teacherLastPageMapper.deleteManageClass(managedClass);//删除课程信息
            List<Score> scores=teacherLastPageMapper.selectManageClassStudentScore(managedClass);//查询该课程下的学生成绩
            if(scores.size()!=0) {
                teacherLastPageMapper.deleteManageClassStudentScore(scores);//删除课程下的学生成绩
            }
            return Result.success("删除成功");
        }catch (Exception e){
            log.error("删除班级失败" + e.getMessage());

            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚事务

            return Result.fail("删除失败"+e.getMessage());
        }
    }
}
